﻿using NETCore.Encrypt;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace Helpers
{
    public class ActionResultHelper
    {
        private static string _encryptKey;

        internal static string EncryptKey { get => _encryptKey ?? throw new Exception("使用前先用ActionResultHelper.InitEncryptKey()初始化"); set => _encryptKey = value; }

        /// <summary>
        /// 初始化加密解密key
        /// </summary>
        /// <param name="key"></param>
        public static void InitEncryptKey(string key)
        {
            EncryptKey = key;
        }

        public static string Encrypt<T>(T value)
        {
            return EncryptProvider.AESEncrypt(JsonConvert.SerializeObject(value), EncryptKey);
        }

        public static T Decrypt<T>(string data)
        {
            var d = EncryptProvider.AESDecrypt(data, EncryptKey);
            if (string.IsNullOrWhiteSpace(d))
            {
                throw new FormatException($"非法参数,{data}");
            }
            return JsonConvert.DeserializeObject<T>(d);
        }

        public static T Decrypt<T>(string data, T type)
        {
            return JsonConvert.DeserializeObject<T>(EncryptProvider.AESDecrypt(data, EncryptKey));
        }
    }
}
